//
//  AppDelegate.m
//  PushTest
//
//  Created by abe on 2017/11/27.
//  Copyright © 2017年 abe. All rights reserved.
//

/**
 *三、这里介绍一下三个Trigger：
 
 分别是：
 UNTimeIntervalNotificationTrigger、UNCalendarNotificationTrigger、UNLocationNotificationTrigger
 
 UNTimeIntervalNotificationTrigger：概括来说，就是在一个指定的时间内，发起推送。可指定一个时间后发起推送，可指定相隔一段时间发起推送。时间由timeInterval决定，是否重复推送由repeats决定。
 UNCalendarNotificationTrigger：在指定的一个日期时间发起通知，比如在星期一的8：30发起一个通知，提醒我要去上班。
 当然，也可以设置为重复推送，即每周一的8：30发起一个通知。具体发起通知的时间由NSDateComponents类决定，具体的文档，大家可以在Xcode查阅。是否重复推送还是由repeats决定。
 UNLocationNotificationTrigger：看这个类的命名，就可以猜测是用来当我们在某个地方时，发起通知。没错，这个类，就是当我们进入一个我们规定的区域时，就给我们发起通知。所规定的区域由CLRegion这个类来决定，创建的方法如下：
 CLRegion *rangedRegions = [[CLCircularRegion alloc] initWithCenter:centerCoordinate radius:50 identifier:@"rangedRegions"];
 传进去的参数有3个，第一个是一个中心，当然这是一个坐标点，需要经纬度，第二个是半径，也就是这个区域的半径，第三个是ID，自定义一个就行。创建好这个区域后，就可以传给CLRegion的创建方法了。是否重复推送还是由repeats决定。意思就是，每次当我进入这个范围的时候，就给我发起一条推送。
 应用好这3个Trigger，还是非常好玩的。
 
 用UNCalendarNotificationTrigger就可以做出类似于苹果"提醒事项"的东西了。
 用
 UNLocationNotificationTrigger也可以做出点好玩的东西，比如，你觉得哪家店的东西很好吃，你就可以将其位置设置为一个范围，当你每次进入该店的一个范围时，手机都会给你推送，“这家店的东西不错。”
 
 作者：kim逸云
 链接：http://www.jianshu.com/p/5da9ceab9306
 來源：简书
 著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
 */

#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>
#import "UMessage.h"

@interface AppDelegate () <UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    // 使用 UNUserNotificationCenter 来管理通知
//    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//    center.delegate = self;
//
//    // 请求授权
//    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
//        NSLog(@"------------->---------requestAuthorizationWithOptions");
//    }];
    
    // 1.请求授权
    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:setting];

    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
//    // 注册一个本地通知
//    [self registerNotification:5.0];
    
    
#pragma  友盟注册通知
 /*   [UMessage startWithAppkey:@"5a1bb9e78f4a9d523000019a" launchOptions:launchOptions];
    //注册通知，如果要使用category的自定义策略，可以参考demo中的代码。
    [UMessage registerForRemoteNotifications];
    
    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate=self;
    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            //这里可以添加一些自己的逻辑
        } else {
            //点击不允许
            //这里可以添加一些自己的逻辑
        }
    }];
    
    //打开日志，方便调试
    [UMessage setLogEnabled:YES];
    */
    return YES;
}

/**
 * 注册一个本地通知
 */
-(void)registerNotification:(NSInteger)alertTime {
    // 1、使用 UNUserNotificationCenter 来管理通知
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    
    // 2、需创建一个包含待通知内容的 UNMutableNotificationContent 对象（可变对象）
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = @"这是一条通知的标题";
    content.body = @"这是一条通知的主体";
    content.sound = [UNNotificationSound defaultSound];
    
    // 在alertTime 后推送本地推送，repeat：是否重复
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:alertTime repeats:NO];
    
    // 新建一个推送请求
    UNNotificationRequest *nRequest = [UNNotificationRequest requestWithIdentifier:@"Notifacation" content:content trigger:trigger];
    
    // 添加推送成功后，弹出提示框
    [center addNotificationRequest:nRequest withCompletionHandler:^(NSError * _Nullable error) {
        
//        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"本地通知" message:@"成功添加推送" preferredStyle:UIAlertControllerStyleAlert];
//
//        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//        [alertVc addAction:cancelAction];
//
//        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVc animated:YES completion:nil];
        
    }];
    
}

#pragma mark - 全新的（iOS10+）推送有两个代理方法，分别是
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    
    NSLog(@"[%s  %d], thread: %@", __func__, __LINE__, [NSThread currentThread]);
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        //关闭U-Push自带的弹出框
        [UMessage setAutoAlert:NO];
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
    
}

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    NSLog(@"[%s  %d], thread: %@", __func__, __LINE__, [NSThread currentThread]);
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于后台时的本地推送接受
    }
    
}

#pragma makr - 获取APNs返回的deviceToken
// 当远程通知注册后。APNs会通过调用这个方法,返回对应的deviceToken
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // 获取到DeviceToken时,将deviceToken值写入到第三方APNs推送服务器PushMeBaby(使用Socket编写的调试服务器),可以在GitHub上下载
    NSLog(@"获取到DeviceToken：%@", deviceToken);
}


-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"[%s  %d], thread: %@", __func__, __LINE__, [NSThread currentThread]);
    NSLog(@"error : %@",error);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    // 注册一个本地通知
//    [self registerNotification:2.0];
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
